package com.shuang.service.impl;

import java.io.IOException;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.shuang.common.FtpUtil;
import com.shuang.common.IDUtils;
import com.shuang.common.UploadData;
import com.shuang.service.FTPService;
@Service("fTPService")
public class FTPServiceImpl implements FTPService {
	//使用spring自带的读取properties文件自动读取相关配置信息注入
	@Value("${FTP_ADDRESS}")
	private String FTP_ADDRESS;
	
	@Value("${FTP_PORT}")
	private Integer  FTP_PORT;
	
	@Value("${FTP_USERNAME}")
	private String FTP_USERNAME;
	
	@Value("${FTP_PASSWORD}")
	private String FTP_PASSWORD;
	
	@Value("${FTP_BASE_PATH}")
	private String FTP_BASE_PATH;
	@Override
	public UploadData imageUpload(MultipartFile uploadFile) {
		UploadData uploadData=null;
		//取原始文件名的后缀名
		String oldName=uploadFile.getOriginalFilename();
		//生成新的文件名
		String filename=IDUtils.genImageName()+oldName.substring(oldName.indexOf("."));
		//文件在服务器的存放路径，应该使用日期分隔的目录结构
		DateTime dateTime = new DateTime();
		String filePath = dateTime.toString("/yyyy/MM/dd");
		//开始上传
		boolean result = false;
		try {
			result = FtpUtil.uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD, FTP_BASE_PATH, filePath, filename, uploadFile.getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
			uploadData=new UploadData(null, null, null, 0, null, "上传失败");
		}
		if(result){
			uploadData=new UploadData(oldName.substring(0,oldName.indexOf(".")),oldName.substring(0,oldName.indexOf(".")),"http://"+FTP_ADDRESS+"/image"+filePath+"/"+filename,uploadFile.getSize(),oldName.substring(oldName.indexOf(".")+1),"SUCCESS");

			
		}else{
			uploadData=new UploadData(null, null, null, 0, null, "上传失败");
		}
		return uploadData;
	}

}
